package servlet;

import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload2.core.DiskFileItemFactory;
import org.apache.commons.fileupload2.core.FileItem;
import org.apache.commons.fileupload2.jakarta.servlet5.JakartaServletFileUpload;

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;

@WebServlet("/upload")
public class FileUploadServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("FileUploadServlet.service()");

        response.setContentType("text/plain;charset=utf-8");

        PrintWriter out=response.getWriter();

        ServletContext application=getServletContext();
        String uploadDir=application.getRealPath("fileupload");

        System.out.println("uploadDir = " + uploadDir);

        DiskFileItemFactory factory=DiskFileItemFactory
                .builder()
                .get();

        JakartaServletFileUpload fileUpload=new JakartaServletFileUpload(factory);

        Map<String, List<FileItem>> formItemMap=fileUpload.parseParameterMap(request);

        String name=formItemMap.get("name").get(0).getString();

        System.out.println("name = " + name);

        FileItem fileItem=formItemMap.get("file").get(0);

        fileItem.write(Paths.get(uploadDir,fileItem.getName()));

        out.print("上传成功");
    }
}


























